<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import userService from '../services/userService'
import type { RegisterRequest } from '../types'

const router = useRouter()

const formData = reactive<RegisterRequest>({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const loading = ref(false)
const error = ref('')
const successMessage = ref('')
const formErrors = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 验证邮箱格式
const isValidEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

// 验证表单
const validateForm = (): boolean => {
  let isValid = true
  
  // 重置错误信息
  Object.keys(formErrors).forEach(key => {
    formErrors[key as keyof typeof formErrors] = ''
  })
  
  // 验证用户名
  if (!formData.username.trim()) {
    formErrors.username = '请输入用户名'
    isValid = false
  } else if (formData.username.length < 3 || formData.username.length > 20) {
    formErrors.username = '用户名长度应在3-20个字符之间'
    isValid = false
  }
  
  // 验证邮箱
  if (!formData.email.trim()) {
    formErrors.email = '请输入邮箱'
    isValid = false
  } else if (!isValidEmail(formData.email)) {
    formErrors.email = '请输入有效的邮箱地址'
    isValid = false
  }
  
  // 验证密码
  if (!formData.password) {
    formErrors.password = '请输入密码'
    isValid = false
  } else if (formData.password.length < 6) {
    formErrors.password = '密码长度至少6个字符'
    isValid = false
  }
  
  // 验证确认密码
  if (!formData.confirmPassword) {
    formErrors.confirmPassword = '请确认密码'
    isValid = false
  } else if (formData.confirmPassword !== formData.password) {
    formErrors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }
  
  return isValid
}

// 处理注册
const handleRegister = async () => {
  if (!validateForm()) {
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    await userService.register(formData)
    
    // 注册成功，显示提示信息
    successMessage.value = '注册成功！请登录'
    
    // 3秒后跳转到登录页面
    setTimeout(() => {
      router.push('/login')
    }, 3000)
  } catch (err: any) {
    error.value = err.response?.data?.message || '注册失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 模拟注册功能（用于演示）
const mockRegister = async () => {
  if (!validateForm()) {
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 注册成功，显示提示信息
    successMessage.value = '模拟注册成功！请登录'
    
    // 3秒后跳转到登录页面
    setTimeout(() => {
      router.push('/login')
    }, 3000)
  } catch (err) {
    error.value = '模拟注册失败'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="register-page">
    <div class="register-container">
      <div class="register-header">
        <h2>创建账号</h2>
        <p>加入海龟汤AI聊天室，开启推理之旅</p>
      </div>
      
      <div class="register-form card">
        <!-- 成功提示 -->
        <div v-if="successMessage" class="success-message">
          {{ successMessage }}
        </div>
        
        <!-- 错误提示 -->
        <div v-else-if="error" class="error-message">
          {{ error }}
        </div>
        
        <form @submit.prevent="handleRegister" v-if="!successMessage">
          <div class="form-group">
            <label for="username">用户名</label>
            <input
              id="username"
              v-model="formData.username"
              type="text"
              placeholder="请输入用户名（3-20个字符）"
              required
              :disabled="loading"
            />
            <div v-if="formErrors.username" class="field-error">
              {{ formErrors.username }}
            </div>
          </div>
          
          <div class="form-group">
            <label for="email">邮箱</label>
            <input
              id="email"
              v-model="formData.email"
              type="email"
              placeholder="请输入邮箱地址"
              required
              :disabled="loading"
            />
            <div v-if="formErrors.email" class="field-error">
              {{ formErrors.email }}
            </div>
          </div>
          
          <div class="form-group">
            <label for="password">密码</label>
            <input
              id="password"
              v-model="formData.password"
              type="password"
              placeholder="请输入密码（至少6个字符）"
              required
              :disabled="loading"
            />
            <div v-if="formErrors.password" class="field-error">
              {{ formErrors.password }}
            </div>
          </div>
          
          <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input
              id="confirmPassword"
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              required
              :disabled="loading"
            />
            <div v-if="formErrors.confirmPassword" class="field-error">
              {{ formErrors.confirmPassword }}
            </div>
          </div>
          
          <div class="form-actions">
            <button
              type="submit"
              class="btn-primary"
              :disabled="loading"
            >
              {{ loading ? '注册中...' : '注册' }}
            </button>
          </div>
        </form>
        
        <!-- 演示注册按钮 -->
        <div v-if="!successMessage" class="demo-section">
          <button
            @click="mockRegister"
            class="btn-demo"
            :disabled="loading"
          >
            演示注册
          </button>
          <p class="demo-tip">点击演示注册可快速体验系统功能</p>
        </div>
        
        <div class="login-link">
          已有账号？<a href="/login">立即登录</a>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.register-page {
  min-height: calc(100vh - 120px);
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.register-container {
  width: 100%;
  max-width: 480px;
  padding: 0 20px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  font-size: 28px;
  color: #262626;
  margin-bottom: 8px;
}

.register-header p {
  color: #666;
  font-size: 16px;
}

.register-form {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 32px;
}

.success-message {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  color: #52c41a;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
  font-size: 16px;
  text-align: center;
}

.error-message {
  background-color: #fff1f0;
  border: 1px solid #ffccc7;
  color: #ff4d4f;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 20px;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.field-error {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.form-actions {
  margin-bottom: 24px;
}

.btn-primary {
  width: 100%;
  padding: 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary:hover:not(:disabled) {
  background-color: #40a9ff;
}

.btn-primary:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.demo-section {
  text-align: center;
  margin-bottom: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.btn-demo {
  width: 100%;
  padding: 12px;
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-demo:hover:not(:disabled) {
  background-color: #e6f7ff;
}

.btn-demo:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.demo-tip {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}

.login-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  color: #40a9ff;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-form {
    padding: 24px;
  }
  
  .register-header h2 {
    font-size: 24px;
  }
}
</style>